package com.mustafaiev.tair.autobase.web.command;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mustafaiev.tair.autobase.dao.WorkerDao;
import com.mustafaiev.tair.autobase.dao.WorkerDaoImpl;
import com.mustafaiev.tair.autobase.db.DBConnector;
import com.mustafaiev.tair.autobase.worker.Worker;

/**
 * 
 * The Command class implements {@link AutobaseServletCommand} and provides
 * worker authorization
 * 
 * @author Tair Mustafaiev
 * 
 */
public class LoginCommandImpl implements AutobaseServletCommand {

    private static final Logger LOG = Logger.getLogger(LoginCommandImpl.class.getName());

    @Override
    public void processGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        req.getSession().getServletContext().getRequestDispatcher("/admin/index.jsp")
                .forward(req, resp);
    }

    @Override
    public void processPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
        Worker worker = new Worker();
        DBConnector connector = DBConnector.getInstance();
        WorkerDao dao = new WorkerDaoImpl();
        dao.setConnector(connector);
        
        if (req.getParameter("email") != null) {
            worker.setEmail(req.getParameter("email").trim());
        }
        if (req.getParameter("pass") != null) {
            worker.setPassword(req.getParameter("pass").trim());
        }

        try {
            
            if (dao.checkWorkerByEmailAndPassword(worker)) {
                req.getSession(true).setAttribute(SESS_AUTH,
                        dao.checkWorkerByEmailAndPassword(worker));
                req.getSession(true).setAttribute("message", "Authorized!");
                resp.sendRedirect("/admin.do");
                LOG.info("Worker with email: " + req.getParameter("email") + " was authorized");

            } else {
                req.getSession(true).setAttribute("error", "Not Authorized!");
                resp.sendRedirect("/index.jsp");
            }

        } catch (SQLException e) {
            LOG.error("Database error at checking user by email and password " + e);

            req.getSession(true).setAttribute("error", "Not Authorized!");
            resp.sendRedirect("/index.jsp");
        }
    }
}
